﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Web;

namespace huaxin_luckdraw.Hubs
{
    public class SessionTimer : IDisposable
    {

        public static double ActivityTimerInterval()
        {
            return 3000.0;
        }


        /// <summary>
        /// 存储客户端对应的Timer
        /// </summary>
        public static readonly ConcurrentDictionary<string, SessionTimer> Timers;


        private readonly Timer _timer;

        static SessionTimer()
        {
            Timers = new ConcurrentDictionary<string, SessionTimer>();
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="connectionId"></param>
        /// <param name="orderNo"></param>
        private SessionTimer(string connectionId,string orderNo)
        {
            _connectionId = connectionId;
            _orderNo = orderNo;

            _timer = new Timer
            {
                Interval = ActivityTimerInterval()
            };
            _timer.Elapsed += (s, e) => MonitorElapsedTime();
            _timer.Start();
        }

        public int TimeCount { get; set; }

        /// <summary>
        /// 客户端连接Id
        /// </summary>
        private string _connectionId { get; set; }

        /// <summary>
        /// 订单号
        /// </summary>
        private string _orderNo { get; set; }


        /// <summary>
        /// 启动Timer
        /// </summary>
        /// <param name="connectionId"></param>
        /// <param name="orderNo"></param>
        public static void StartTimer(string connectionId,string orderNo)
        {
            var newTimer = new SessionTimer(connectionId,orderNo);
            if (!Timers.TryAdd(connectionId, newTimer))
            {
                newTimer.Dispose();
            }
        }

        /// <summary>
        /// 停止Timer
        /// </summary>
        /// <param name="connectionId"></param>
        public static void StopTimer(string connectionId)
        {
            SessionTimer oldTimer;
            if (Timers.TryRemove(connectionId, out oldTimer))
            {
                oldTimer.Dispose();
            }
        }

        public void Dispose()
        {
            // Stop might not be necessary since we call Dispose
            _timer.Stop();
            _timer.Dispose();
        }

        /// <summary>
        ///开始查询订单状态
        /// </summary>
        private void MonitorElapsedTime()
        {

            Notifier.getOrderNoHandle(_connectionId,_orderNo);

            //TimeCount++;
            //if (TimeCount > 1000)
            //{
            //    TimeCount = 0;
            //}
        }

    }
}